﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AutoLoginAndRun
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            const string ElevatedFlag = "SaveLogin";

            bool saveSettings = args != null && args.Length > 0 && args[0].Equals(ElevatedFlag); // will set AutoLogin?
            if (saveSettings)
            {
                bool result = RegistryHelper.SetAutoLogin();
                return result ? 0 : -1;
            }
            else
            {
                bool canWrite1;
                RegistryHelper.GetAutoLogin(out canWrite1);
                bool canWrite2;
                RegistryHelper.GetAutoStart(out canWrite2);

                bool elevationNeeded = canWrite1 == false || canWrite2 == false;

                MainForm frm = new MainForm(elevationNeeded);

                Application.Run(frm);

                if (frm.DialogResult == DialogResult.OK)
                {
                    RegistryHelper.SetAutoStart();

                    if (elevationNeeded)
                    {
                        #region run as Admin with "SaveSettings" flag
                        // Ececutar o aplicativo como Administrador e com o argumento "SetAutoLogin" para
                        // alterar a configuracao de login. Apos a alteracao, o aplicativo fecha.

                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                        startInfo.FileName = Application.ExecutablePath;
                        startInfo.Arguments = ElevatedFlag;
                        startInfo.Verb = "runas";
                        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                        using (System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo))
                        {
                            process.WaitForExit(5000);
                            if (process.HasExited == false)
                            {
                                process.Kill();
                            }

                            return process.ExitCode;
                        }

                        #endregion
                    }
                }

                return 0;
            }
        }
    }
}
